package de.alt.rest.handler;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

import de.alt.rest.constants.Constants;

/**
 * The Class SwitchHandler.
 */
public class SwitchHandler {

	/**
	 * Do switch.
	 *
	 * @param key the key
	 * @param value the value
	 * @return the map
	 */
	public Map<String, Boolean> doSwitch(String key, String value) {
		return putStateToMemCache(key, value);
	}
	
	/**
	 * Gets the switch status.
	 *
	 * @return the switch status
	 */
	public Map<String, Boolean> getSwitchStatus() {
		return getStateFromMemCache();
	}

	/**
	 * Put state to mem cache.
	 * 
	 * @param key the key
	 * @param value the value
	 * @return the string
	 */
	private Map<String, Boolean> putStateToMemCache(String key, String value) {
		Map<String, Boolean> state = getStateFromMemCache();
		state.put(key, new Boolean(value));
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
		syncCache.put(Constants.MEMCACHEKEY_SWITCH_STATE, state);
		return state;
	}

	/**
	 * Gets the state from mem cache.
	 * 
	 * @return the state from mem cache
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Boolean> getStateFromMemCache() {
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));

		if (syncCache.get(Constants.MEMCACHEKEY_SWITCH_STATE) == null) {
			return new HashMap<String, Boolean>();
		}
		return (Map<String, Boolean>) syncCache.get(Constants.MEMCACHEKEY_SWITCH_STATE);
	}

}
